package com.chhuang.ewcrm.ctrl;

import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.application.RootApp;
import com.chhuang.ewcrm.config.PropertiesUtil;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.thread.AddLogThread;
import com.chhuang.ewcrm.utils.AutoCompleteComboBoxListener;
import com.chhuang.ewcrm.utils.LengthTextFilter;
import com.chhuang.ewcrm.utils.MyAlert;
import com.chhuang.ewcrm.vo.ResultBean;
import com.jfoenix.controls.JFXButton;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import static javafx.application.Platform.runLater;

/**
 * 登录页面控制类
 * @author chhuang
 * @create 2020-09-11-10:02
 */
public class WLoginController implements Initializable {
    private final Logger logger = LoggerFactory.getLogger(WLoginController.class);
    @FXML
    private JFXButton loginButton;
    @FXML
    private PasswordField passwordField;
    @FXML
    private ComboBox<String> usernameComboBox;

    public WLoginController(){}

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        AppRequest.getInstance().getService().getWeighMans()
            .compose(ServiceRxSchedulers.compose())
            .subscribe(new ServiceSubscriber<>("获取用户登录名请求") {
                @Override
                protected void onHandleSuccess(List<String> names) {
                    if(names!=null && !names.isEmpty()) {
                        runLater(()-> {
                            usernameComboBox.getItems().addAll(names);
                            new AutoCompleteComboBoxListener<>(usernameComboBox);
                            usernameComboBox.getSelectionModel().select(0);
                        });
                    }
                }
            });

    }

    /**
     * 登录
     * @param event
     */
    @FXML
    private void login(Event event){
        loginButton.setDisable(true);

        usernameComboBox.getEditor().setTextFormatter(new TextFormatter<>(new LengthTextFilter(127)));
        String username = usernameComboBox.getValue();
        if(StringUtils.isEmpty(username)){
            MyAlert.showError("错误","登录出错","请输入用户名");
            loginButton.setDisable(false);
            usernameComboBox.requestFocus();
            return;
        }
        String password = passwordField.getText();
        if(StringUtils.isEmpty(password)){
            MyAlert.showError("错误","登录出错","请输入密码");
            loginButton.setDisable(false);
            passwordField.requestFocus();
            return;
        }

        AppRequest.getInstance().getService().login(username, password)
            .compose(ServiceRxSchedulers.compose())
            .subscribe(new ServiceSubscriber<>("登录请求") {
                @Override
                protected void onHandleSuccess(SysUser sysUser) {
                    AppRequest.getInstance().createService(sysUser.getWsLoginToken());//设置登录后的请求头 带token
                    Constants.loginUser = sysUser;//保存本地内存用户信息
//                    logger.debug("登录成功："+Constants.loginUser.toString());
                    new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                            Constants.loginUser.getUsername(),
                            Constants.loginUser.getFullname(),
                            "登录成功")).start();
                    runLater(()->RootApp.open((Stage) ((Node) event.getSource()).getScene().getWindow()));
                }

                @Override
                protected void onHandleError(ResultBean<SysUser> error) {
                    super.onHandleError(error);
                    loginButton.setDisable(false);
                }
            });
    }

    @FXML
    public void translateStart(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER && !loginButton.isDisable()) {//回车登录
//            RootApp.open((Stage) ((Parent)event.getSource()).getScene().getWindow());
            login(event);
        }
    }

}
